package com.algorithm.ch1.lzr.string;

/**
 * 有效的字母异位词 字符串只包含小写字母
 * <p>
 * 输入: s = "anagram", t = "nagaram"
 * 输出: true
 * <p>
 * 输入: s = "rat", t = "car"
 * 输出: false
 * <p>
 * 思考: 如果输入字符串包含 unicode 字符
 *
 * @author lzr
 * @date 2018/8/13
 */
public class IsAnagram {
    public static void main(String[] args) {
        String s1 = "anagram";
        String t1 = "nagaram";
        boolean anagram1 = isAnagram1(s1, t1);
        System.out.println(anagram1);
        String s2 = "rat";
        String t2 = "car";
        boolean anagram2 = isAnagram1(s2, t2);
        System.out.println(anagram2);
        String s3 = "";
        String t3 = "";
        boolean anagram3 = isAnagram1(s3, t3);
        System.out.println(anagram3);
    }


    /**
     * 有效的字母异位词  利用s.toCharArray()比for循环将String转成数组的方式要快
     *
     * @param s
     * @param t
     * @return
     */
    public static boolean isAnagram1(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        if (s.length() == 0) {
            return true;
        }
        int[] ints = new int[26];
        char[] sChars = s.toCharArray();
        for (char c : sChars) {
            ints[c - 97]++;
        }
        /*
        for (int i = 0; i < s.length(); i++) {
            ints[s.charAt(i)-97]++;
        }
        */
        char[] tChars = t.toCharArray();
        for (char c : tChars) {
            ints[c - 97]--;
        }
        /*
        for (int i = 0; i < t.length(); i++) {
            ints[t.charAt(i)-97]--;
        }
        */
        for (int c : ints) {
            if (c != 0) {
                return false;
            }
        }
        return true;
    }

}
